package com.ysd.lis.service.qc.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.lab.LabInstrSetup;
import com.ysd.lis.entity.lab.LabItemDict;
import com.ysd.lis.entity.qc.QcInstrItem;
import com.ysd.lis.entity.qc.QcInstrItemRule;
import com.ysd.lis.entity.qc.QcInstrSample;
import com.ysd.lis.entity.qc.QcMaterial;
import com.ysd.lis.mapper.lab.LabInstrSetupMapper;
import com.ysd.lis.mapper.qc.QcInstrItemMapper;
import com.ysd.lis.mapper.qc.QcInstrItemRuleMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.qc.QcInstrItemDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.qc.QcInstrItemService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2021-10-08
 */
@Service
@Slf4j
public class QcInstrItemServiceImpl extends ServiceImpl<QcInstrItemMapper, QcInstrItem> implements QcInstrItemService {
    @Autowired
    QcInstrItemMapper qcInstrItemMapper;
    @Autowired
    LabInstrSetupMapper labInstrSetupMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    QcInstrItemRuleMapper qcInstrItemRuleMapper;
    @Override
    public Result findInstrClassAndInstrList(CommonPageDto pageParam) {

        LambdaQueryWrapper<LabInstrSetup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabInstrSetup::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabInstrSetup::getInstrName, pageParam.getSeachValue())
                    .or().like(LabInstrSetup::getInstrCode, pageParam.getSeachValue()));
        }
        if(ToolsUtils.isNotEmpty(pageParam.getPoct())){
            lambdaQueryWrapper.eq(LabInstrSetup::getPoct,pageParam.getPoct());
        }
        List<LabInstrSetup> instrSetupList = labInstrSetupMapper.selectList(lambdaQueryWrapper);
        List<Map> iList = new ArrayList<>();
        for(LabInstrSetup instrSetup : instrSetupList){
            Map<String,Object> map = new HashMap<>();
            map.put("id",instrSetup.getId());
            map.put("instrName",instrSetup.getInstrName());
            map.put("instrCode",instrSetup.getInstrCode());
            map.put("instrClass",instrSetup.getInstrClass());
            map.put("rptGroup",instrSetup.getRptGroup());
            map.put("isSearch","0");
            iList.add(map);
        }
        List<String> classList = instrSetupList.stream().filter(ins-> ToolsUtils.isNotEmpty(ins.getInstrClass()) ).map(LabInstrSetup::getInstrClass).distinct().collect(Collectors.toList());
        //查字典
        List<Map<String, Object>> yqdllist = (List<Map<String, Object>>)sysBasDictDetailService.getSysBasDictList("YQDL").getData();
        List<Map>  returnList = new ArrayList<>();
        for(int i = 0;i<classList.size() ;i++){
            String className = classList.get(i);
            Map<String,Object> map = new HashMap();
            map.put("id",i+1);
            map.put("instrCode",className);
            map.put("instrName",yqdllist.stream().filter(a->a.get("code").equals(className)).findFirst().get().get("name"));
            map.put("children",iList.stream().filter(is -> ToolsUtils.isNotEmpty(is.get("instrClass"))&&is.get("instrClass").equals(className)).collect(Collectors.toList()));
            map.put("isSearch","1");
            returnList.add(map);
        }
        return Result.succ(1, "查询成功", returnList);
    }

    @Override
    public Result findInstrAndInstrItemTree(CommonPageDto pageParam) {
        LambdaQueryWrapper<LabInstrSetup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabInstrSetup::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabInstrSetup::getInstrName, pageParam.getSeachValue())
                    .or().like(LabInstrSetup::getInstrCode, pageParam.getSeachValue()));
        }
        if(ToolsUtils.isNotEmpty(pageParam.getInstrId())){
            lambdaQueryWrapper.eq(LabInstrSetup::getId,pageParam.getInstrId());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getPoct())){
            lambdaQueryWrapper.eq(LabInstrSetup::getPoct,pageParam.getPoct());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getInstrIds())){
            lambdaQueryWrapper.in(LabInstrSetup::getId,pageParam.getInstrIds());
        }
        lambdaQueryWrapper.orderByAsc(LabInstrSetup::getCreateTime);
        List<LabInstrSetup> instrSetupList = labInstrSetupMapper.selectList(lambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(instrSetupList)){
            //根据仪器查出仪器下得质控项目

            MPJLambdaWrapper<QcInstrItem> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(QcInstrItem.class)
                    .selectAs("ld", LabItemDict::getItemNo,QcInstrItem::getItemDictCode)
                    .selectAs("ld", LabItemDict::getItemNa,QcInstrItem::getItemDictName)
                    .selectAs("ld", LabItemDict::getItemEnCode,QcInstrItem::getItemEnCode)
                    .selectAs("ld", LabItemDict::getItemClass,QcInstrItem::getItemClass)
                    .selectAs("ld", LabItemDict::getInputCode,QcInstrItem::getInputCode)
                    .selectAs("ld", LabItemDict::getReportCode,QcInstrItem::getReportCode)
                    .selectAs("ld", LabItemDict::getInstrClass,QcInstrItem::getInstrClass)
                    .leftJoin(LabItemDict.class,"ld",LabItemDict::getId,QcInstrItem::getItemDictId)
                    .in(QcInstrItem::getInstrId,instrSetupList.stream().map(LabInstrSetup::getId).collect(Collectors.toList()))
                    .eq(QcInstrItem::getDelFlag,0)
                    .orderByAsc(QcInstrItem::getSeq);
            List<QcInstrItem> itemList = qcInstrItemMapper.selectList(queryWrapper);
            List<Map> imList = new ArrayList<>();
            for(QcInstrItem item : itemList){
                Map<String,Object> map = new HashMap<>();
                map.put("id",item.getId());
                map.put("name",item.getItemDictName());
                map.put("code",item.getItemEnCode());
                map.put("instrId",item.getInstrId());
                map.put("isSearch","0");
                map.put("type","instrItem");
                imList.add(map);
            }

            List<Map> iList = new ArrayList<>();
            for(LabInstrSetup instrSetup : instrSetupList){
                Map<String,Object> map = new HashMap<>();
                map.put("id",instrSetup.getId());
                map.put("name",instrSetup.getInstrName());
                map.put("code",instrSetup.getInstrCode());
                map.put("instrClass",instrSetup.getInstrClass());
                map.put("children",imList.stream().filter(is -> is.get("instrId").equals(instrSetup.getId())).collect(Collectors.toList()));
                map.put("isSearch","0");
                map.put("type","instr");
                iList.add(map);
            }
            List<String> classList = instrSetupList.stream().filter(ins-> ToolsUtils.isNotEmpty(ins.getInstrClass()) ).map(LabInstrSetup::getInstrClass).distinct().collect(Collectors.toList());

            //查字典
            List<Map<String, Object>> yqdllist = (List<Map<String, Object>>)sysBasDictDetailService.getSysBasDictList("YQDL").getData();

            List<Map>  returnList = new ArrayList<>();
            for(int i = 0;i<classList.size() ;i++){
                String className = classList.get(i);
                Map<String,Object> map = new HashMap();
                map.put("id",i+1);
                map.put("code",className);
                map.put("name",yqdllist.stream().filter(a->a.get("code").equals(className)).findFirst().get().get("name"));
                map.put("children",iList.stream().filter(is -> ToolsUtils.isNotEmpty(is.get("instrClass"))&&is.get("instrClass").equals(className)).collect(Collectors.toList()));
                map.put("isSearch","1");
                map.put("type","instrClass");
                returnList.add(map);
            }
            return Result.succ(1, "查询成功", returnList);

        }
        return Result.succ(1, "更新成功", null);
    }

    @Override
    public Result batchUpdateQcInstrItemList(QcInstrItemDto dto) {
        List<QcInstrItem> qcInstrItemList = dto.getQcInstrItemList();
        boolean b = this.updateBatchById(qcInstrItemList);
        if (b) {
            return Result.succ(1, "成功", null);
        } else {
            return Result.fail(400, "失败", "");
        }
    }

    @Override
    public Result findQcInstrItemList(CommonPageDto pageParam) {
        MPJLambdaWrapper<QcInstrItem> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(QcInstrItem.class)
                    .selectAs("ld", LabItemDict::getItemNo,QcInstrItem::getItemDictCode)
                    .selectAs("ld", LabItemDict::getItemNa,QcInstrItem::getItemDictName)
                    .selectAs("ld", LabItemDict::getItemEnCode,QcInstrItem::getItemEnCode)
                    .selectAs("ld", LabItemDict::getItemClass,QcInstrItem::getItemClass)
                    .selectAs("ld", LabItemDict::getInputCode,QcInstrItem::getInputCode)
                    .selectAs("ld", LabItemDict::getReportCode,QcInstrItem::getReportCode)
                    .selectAs("ld", LabItemDict::getInstrClass,QcInstrItem::getInstrClass)
                    .leftJoin(LabItemDict.class,"ld",LabItemDict::getId,QcInstrItem::getItemDictId)
                    .eq(QcInstrItem::getInstrId,pageParam.getPid())
                    .eq(QcInstrItem::getDelFlag,0)
                    .orderByAsc(QcInstrItem::getSeq);
        List<QcInstrItem> itemList = qcInstrItemMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", itemList);
    }

    @Override
    public Result batchAddQcInstrItemList(QcInstrItemDto dto) {
        List<QcInstrItem> qcInstrItemList = dto.getQcInstrItemList();
        boolean b = this.saveBatch(qcInstrItemList);
        if(b){
            return Result.succ(1, "添加成功", null);
        }else {
            return Result.fail(400,"添加失败","");
        }
    }

    @Override
    public Result batchDeleteQcInstrItemList(QcInstrItemDto dto) {
        List<QcInstrItem> qcInstrItemList = dto.getQcInstrItemList();
        List<String> ids = qcInstrItemList.stream().map(QcInstrItem::getId).collect(Collectors.toList());
        //根据仪器质控项目ID查询是否有仪器质控规则，有则不能删除
        LambdaQueryWrapper<QcInstrItemRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QcInstrItemRule::getDelFlag,0)
                .in(QcInstrItemRule::getPid,ids);
        Integer cnt = qcInstrItemRuleMapper.selectCount(queryWrapper);
        if(cnt>0){
            return Result.succ(1, "质控项目下有质控规则，不能删除", null);
        }else{
            boolean b = this.removeByIds(ids);
            if(b){
                return Result.succ(1, "删除成功", null);
            }else {
                return Result.fail(400,"删除失败","");
            }
        }
    }
}
